--[[
FilePath: \Lua\View\UIHeroCollect\UIHeroCollect.lua
英雄集结
--]]

require 'View/UIBase/UIBase'
require "View/CharactorUI/UIBreakStone"

UIHeroCollect = UIBase.New(PanelResNames.UIHeroCollect)
local _M = UIHeroCollect

_M.hasInit = false
_M.ContentItems = {}
_M.selectIndex = 0
_M.tabRed = {}
_M.activeId = nil
_M.activityTabConfig = nil
_M.tableModel = nil
_M.isGetReward = false;
_M.playEffect = false;
_M.lastRewardedTime = -1;

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

-- 创建回调
function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("btnBack"), self.OnBack)
        self.btnR = self:GetChild("btnR");
        self.btnR.name = "btnR";
        table.insert(_M.tabRed, self.btnR:GetChild("UIRedDots"):GetController("c1")) 
        self.btnSR = self:GetChild("btnSR");
        self.btnSR.name = "btnSR";
        table.insert(_M.tabRed, self.btnSR:GetChild("UIRedDots"):GetController("c1"))
        self.btnSSR = self:GetChild("btnSSR");
        self.btnSSR.name = "btnSSR";
        table.insert(_M.tabRed, self.btnSSR:GetChild("UIRedDots"):GetController("c1"))
        self.btnLR = self:GetChild("btnLR");
        self.btnLR.name = "btnLR";
        table.insert(_M.tabRed, self.btnLR:GetChild("UIRedDots"):GetController("c1"))

        self.boxReward = {}
        for i = 1, 6 do
            local singleBox = self:GetChild("Node" .. tostring(i))
            table.insert(self.boxReward, singleBox);
        end
        self.totalTaskInfo = self:GetChild("TotaltaskInfo");
        self.countDown = self:GetChild("CountDown");
        self.boxProgress = self:GetChild("fill");
        self.firstBoxProgress = self:GetChild("fill1");
        self.taskList = self:GetChild("btnlist");

        self.btnHelp = self:GetChild("help");

        self.bannerText = self:GetChild("bannerText")
        self.title = self:GetChild("title")
        self.ResBar = self:GetChild("ResBar");
        self.heroController = self:GetController("hero");
        self.btnGetAllReward = self:GetChild("ConfirmBtn");
        self.allRewardState = self:GetController("status");

        --self.btnGiftDay = self:GetChild("giftday");
        --self.giftDayNum = self.btnGiftDay:GetChild("num");
        --self.giftDayState = self.btnGiftDay:GetController("status");
        self.skinBtn = self:GetChild("skinBtn");

        if self.activeId ~= nil then
            _M.activityTabConfig = G.dataTable["t_activitylist"][tostring(self.activeId)];
            _M.tableModel = G.dataTable["t_assembletaskmodel"][tostring(self.activeId)];
        end
        _M.isGetReward = false;
        _M.hasInit = true
        self:showLanguage()
        self:addEvent()
    end
end

function _M:showLanguage()
    if _M.activityTabConfig ~= nil and _M.activityTabConfig.f_Title ~= nil then
        self.title.text = getLanguage(tostring(_M.activityTabConfig.f_Title));
    end

    self.bannerText.text = getLanguage("ActivityDesc1050104");
    
    self.btnR:GetChild("title").text = getLanguage("ActivitytTask1050101");
    self.btnSR:GetChild("title").text = getLanguage("ActivitytTask1050102");
    self.btnSSR:GetChild("title").text = getLanguage("ActivitytTask1050103");
    self.btnLR:GetChild("title").text = getLanguage("ActivitytTask1050104");

    self.ResBar.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"]["1"].f_Icon;
end

function _M:addEvent()
    self.btnR.onClick:Add(self.ChangeR)
    self.btnSR.onClick:Add(self.ChangeSR)
    self.btnSSR.onClick:Add(self.ChangeSSR)
    self.btnLR.onClick:Add(self.ChangeLR)

    self.btnHelp.onClick:Add(self.HelpTip)

    --self.btnGiftDay.onClick:Add(self.GetGiftDay)
    self.btnGetAllReward.onClick:Add(self.GetAllReward)
    self.skinBtn.onClick:Add(self.onClickSkin)

    self:RegisterEvent(Config.EventType.Fresh_Active,self.RefreshActive);
    --UIRedDots.addViewListen(PanelNames.UIHeroCollect, "tag" .. btnR.name, btnR, Config.RedDotsType.Task, 1);
   -- UIRedDots.addViewListen(PanelNames.UIHeroCollect, "tag" .. btnSR.name, btnSR, Config.RedDotsType.Task, 2);
   -- UIRedDots.addViewListen(PanelNames.UIHeroCollect, "tag" .. btnSSR.name, btnSSR, Config.RedDotsType.Task, 3);
   -- UIRedDots.addViewListen(PanelNames.UIHeroCollect, "tag" .. btnLR.name, btnLR, Config.RedDotsType.TimeBoxAll, 4);
end 

function _M:removeEvent()
    self.btnR.onClick:Remove(self.ChangeR)
    self.btnSR.onClick:Remove(self.ChangeSR)
    self.btnSSR.onClick:Remove(self.ChangeSSR)
    self.btnLR.onClick:Remove(self.ChangeLR)

    self.btnHelp.onClick:Remove(self.HelpTip)

    --self.btnGiftDay.onClick:Remove(self.GetGiftDay)
    self.btnGetAllReward.onClick:Remove(self.GetAllReward)
    self.skinBtn.onClick:Remove(self.onClickSkin)
    --UIRedDots.removeViewEvent(PanelNames.UIHeroCollect)
end

function _M.ChangeR()
    if _M.selectIndex == 0 then
        return;
    end
    _M.playEffect = true;
    _M.selectIndex = 0;
    _M:Refresh();
end

function _M.ChangeSR()
    if _M.selectIndex == 1 then
        return;
    end
    _M.playEffect = true;
    _M.selectIndex = 1;
    _M:Refresh();
end

function _M.ChangeSSR()
    if _M.selectIndex == 2 then
        return;
    end
    _M.playEffect = true;
    _M.selectIndex = 2;
    _M:Refresh();
end

function _M.ChangeLR()
    if _M.selectIndex == 3 then
        return;
    end
    _M.playEffect = true;
    _M.selectIndex = 3;
    _M:Refresh();
end

function _M.HelpTip()
    if _M.activityTabConfig ~= nil and _M.activityTabConfig.f_ExplainTitle ~= nil and _M.activityTabConfig.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(_M.activityTabConfig.f_ExplainTitle), tostring(_M.activityTabConfig.f_ExplainText));
    end
end

function _M.GetGiftDay()
    if  _M.isGetReward then
        print("快速点击")
        return;
    end
    print("领取每日奖励")
    _M.isGetReward = true;
    --ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, 3});
    _M:TimeCall(_M.GetRewardTimeEnd, 100);
end

function _M.GetAllReward()
    if  _M.isGetReward then
        return;
    end
    _M.isGetReward = true;
    ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, 0, _M.selectIndex});
    _M:TimeCall(_M.GetRewardTimeEnd, 100);
end

function _M.onClickSkin()
    if _M.tableModel ~= nil and _M.tableModel.f_HeroId ~= nil and _M.tableModel.f_HeroSkinId ~= nil then
        local heroData = logicMgr.HeroManager.getHeroDatabyModelId(_M.tableModel.f_HeroId,false);
        if heroData ~= nil then
            showUI(PanelNames.UIHeroFashionShow, heroData, _M.tableModel.f_HeroSkinId, 2);
        end
    end
end

-- 显示
function _M:OnEnable()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
        self.playEffect = true;
        _M.assembleTaskList = nil;
        --self:Refresh();
        self:RefreshBox();
        self:RefreshTabRed(true);
        self:RefreshToken();
        --self:RefreshDailyReward();
    end
end

function _M:RefreshActive()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
        self.playEffect = false;
        _M.assembleTaskList = nil;
        --self:Refresh();
        self:RefreshBox();
        self:RefreshTabRed(false);
        self:RefreshToken();
        self:RefreshDailyReward();
    end
end

function _M:RefreshDailyReward()
    --local rewards = G.dataTable["t_global"][tostring(360)].f_string_value;
    --rewards = decodeJsonStrToTabel(rewards)
    --self.giftDayNum.text = tostring(rewards[1][2]);
    local state = tonumber(self.serverData.dailyRewardState);
    local rewardTime = 0;
    if self.serverData.param ~= nil and self.serverData.param.lastRewardedTime ~= nil then
        rewardTime = tonumber(self.serverData.param.lastRewardedTime);
    end
    if state == -1 then
        self:Refresh();
        --self.giftDayState.selectedIndex = 3;
        if self.lastRewardedTime > -1 and self.lastRewardedTime ~= rewardTime then
            self.lastRewardedTime = -1;
            --打开弹框
            showUI(PanelNames.UIHeroCollectReward)
        end
    else
       -- self.giftDayState.selectedIndex = state;
        self.lastRewardedTime = rewardTime;
        self.isGetReward = true;
        ActivityHandler.sendReqActivityDrawRewardMessage({self.activeId, 3, 0});
        self:TimeCall(self.GetRewardTimeEnd, 100);
    end
end

function _M:RefreshToken()
    local haveNum = logicMgr.ItemManager.getBagNumByTableID(1);
    self.ResBar.title = haveNum;
end

function _M:RefreshTabRed(needRefresh)
    local assembleTaskMap = self.serverData.param.assembleTaskMap;
    local tabRedIndex = 0;
    if assembleTaskMap ~= nil then
        local tabStatue = {};
        for k, v in pairs(assembleTaskMap) do
            local localAssembleTask = G.dataTable["t_assembletask"][tostring(k)];
            if localAssembleTask ~= nil then
                if localAssembleTask.f_Remark == nil or localAssembleTask.f_Remark == 0 then
                    localAssembleTask.f_Remark = 0
                end
                if tabStatue[tonumber(localAssembleTask.f_Remark)] == nil then
                    tabStatue[tonumber(localAssembleTask.f_Remark)] = {}
                end
                if tonumber(localAssembleTask.f_Show) == 1 then
                    if not v.rewarded and tonumber(v.process) >= tonumber(localAssembleTask.f_Progress) then
                        table.insert(tabStatue[tonumber(localAssembleTask.f_Remark)], 1)
                        _M.UploadTaskFinish(localAssembleTask.f_AssembleTaskId)
                    else
                        table.insert(tabStatue[tonumber(localAssembleTask.f_Remark)], 0)
                    end
                else
                    table.insert(tabStatue[tonumber(localAssembleTask.f_Remark)], 0)
                end
            end
        end
        
        for i = 1, #_M.tabRed do
            _M.tabRed[i].selectedIndex = 0;
            local statueData = tabStatue[tonumber(i - 1)];
            for j = 1, #statueData do
                if statueData[j] == 1 then
                    _M.tabRed[i].selectedIndex = 2;
                    if tonumber(tabRedIndex) == 0 then
                        tabRedIndex = i;
                    end
                    break;
                end
            end
        end
    end
    if needRefresh ~= nil and needRefresh then
        if tabRedIndex > 0 then
            _M.selectIndex = tonumber(tabRedIndex) - 1;
        else
            _M.selectIndex = 0;
        end
        self.heroController:SetSelectedIndex(tonumber(_M.selectIndex));
        --self:Refresh();
        self:RefreshDailyReward();
    end
end

--上传完成且没有领取的任务
function _M.UploadTaskFinish(id)
    TAManager.TrackByDictionary("assembly_task_finish", {assembletask_id = id})
end

_M.assembleTaskList = nil
_M.assembleTaskServerData = nil;
_M.rewardedNum = 0;
_M.taskNum = 0;
_M.hasTaskReward = false;
function _M:Refresh()
    local localAssembleTask = G.dataTable["t_assembletask"];
    if _M.assembleTaskList == nil and self.serverData.param.assembleTaskMap ~= nil then
        _M.assembleTaskList = {};
        _M.assembleTaskServerData = nil;
        _M.assembleTaskServerData = {};
        local assembleTaskMap = self.serverData.param.assembleTaskMap;
        _M.rewardedNum = 0;
        _M.taskNum = 0;
        _M.hasTaskReward = false;

        local rTask = {}
        local srTask = {}
        local ssrTask = {}
        local lrTask = {}
        local enumTask = {}
        for k, v in pairs(assembleTaskMap) do
            _M.taskNum = _M.taskNum + 1;
            local assembleTaskConfig = localAssembleTask[tostring(k)]
            if assembleTaskConfig.f_Remark == nil or assembleTaskConfig.f_Remark == 0 then
                assembleTaskConfig.f_Remark = 0
            end
            if enumTask[tonumber(assembleTaskConfig.f_Remark)] == nil then
                enumTask[tonumber(assembleTaskConfig.f_Remark)] = {}
            end
            if enumTask[tonumber(assembleTaskConfig.f_Remark)][assembleTaskConfig.f_AssembleTaskEnum] == nil then
                enumTask[tonumber(assembleTaskConfig.f_Remark)][assembleTaskConfig.f_AssembleTaskEnum] = {}
            end
            if tonumber(assembleTaskConfig.f_Show) == 0 then
                table.insert(enumTask[tonumber(assembleTaskConfig.f_Remark)][assembleTaskConfig.f_AssembleTaskEnum], assembleTaskConfig.f_PreAssembleTaskId)
                local localDataServer = {process = assembleTaskConfig.f_Progress, rewarded = true };
                _M.rewardedNum = _M.rewardedNum + 1;
                _M.assembleTaskServerData[tostring(assembleTaskConfig.f_PreAssembleTaskId)] = localDataServer;
            else
                table.insert(enumTask[tonumber(assembleTaskConfig.f_Remark)][assembleTaskConfig.f_AssembleTaskEnum], assembleTaskConfig.f_AssembleTaskId)
                _M.assembleTaskServerData[tostring(assembleTaskConfig.f_AssembleTaskId)] = v;
                if v.rewarded then
                    _M.rewardedNum = _M.rewardedNum + 1;
                elseif tonumber(v.process) >= tonumber(assembleTaskConfig.f_Progress) then
                    _M.hasTaskReward = true;
                end
            end
        end
        for i = 0, #enumTask do
            for k, v in pairs(enumTask[i]) do
                table.sort(v)
                if i == 0 then
                    table.insert(rTask, v)
                elseif i == 1 then
                    table.insert(srTask, v)
                elseif i == 2 then
                    table.insert(ssrTask, v)
                elseif i == 3 then
                    table.insert(lrTask, v)
                end
            end
        end
        table.sort(rTask, function (a, b)
            return a[1] < b[1]; 
        end)
        table.insert(_M.assembleTaskList, rTask);
        table.sort(srTask, function (a, b)
            return a[1] < b[1];
        end)
        table.insert(_M.assembleTaskList, srTask);
        table.sort(ssrTask, function (a, b)
            return a[1] < b[1];
        end)
        table.insert(_M.assembleTaskList, ssrTask);
        table.sort(lrTask, function (a, b)
            return a[1] < b[1];
        end)
        table.insert(_M.assembleTaskList, lrTask);
    end
    
    self.taskList.itemRenderer = self.RefreshTaskItem;
    if _M.assembleTaskList ~= nil then
        local assembleTask = _M.assembleTaskList[_M.selectIndex + 1];
        local assembleTaskNum =  #assembleTask;
        self.taskList.numItems = assembleTaskNum;
        if self.playEffect then
            HelperFunc.ListTranstionPlay(self.taskList)
        end
        --[[
        local rewardedNum = 0;
        local rewardNum = 0;
        for k,v in pairs(assembleTask) do
           local taskData =  self.assembleTaskServerData[tostring(v[1])]
            if taskData.rewarded then
                rewardedNum = rewardedNum + 1;
            else
                local config = localAssembleTask[tostring(v[1])];
                if tonumber(taskData.process) >= tonumber(config.f_Progress) then
                    rewardNum = rewardNum + 1;
                end
            end
        end
        if rewardedNum == assembleTaskNum then
            self.allRewardState.selectedIndex = 2;
        elseif rewardNum > 0 then
            self.allRewardState.selectedIndex = 1;
        else
            self.allRewardState.selectedIndex = 0;
        end
        --]]
    else
        self.taskList.numItems = 0;
    end
    if _M.assembleTaskList == nil then
        self.allRewardState.selectedIndex = 0;
    elseif _M.rewardedNum == _M.taskNum then
        self.allRewardState.selectedIndex = 2;
    elseif _M.hasTaskReward then
        self.allRewardState.selectedIndex = 1;
    else
        self.allRewardState.selectedIndex = 0;
    end
end

_M.assembleTaskBoxConfig = nil
_M.boxStatus = nil
_M.boxRewardItem = nil
--_M.boxRewardItemCtrl = nil
--_M.heroId = nil
_M.boxMaxCount = 0;
_M.firstBoxCount = 200;
_M.specialRewardEndTime = 0;
_M.endCountDown = 0;
function _M:RefreshBox()
    if _M.assembleTaskBoxConfig == nil then
        _M.assembleTaskBoxConfig = G.dataTable["t_assembletaskbox"];
        table.sort(_M.assembleTaskBoxConfig, function(a, b)
            return a.f_NeedExpCount < b.f_NeedExpCount
        end);
        _M.boxStatus = {}
        _M.boxRewardItem = {}
       -- _M.boxRewardItemCtrl = {}
        for i = 1, #self.boxReward do
            local boxConfig = _M.assembleTaskBoxConfig[tostring(i)];
            local tempNum = _M.boxReward[i]:GetChild("num");
            if i == 1 then
                _M.firstBoxCount = boxConfig.f_NeedExpCount;
            end
            if tonumber(_M.boxMaxCount) < tonumber(boxConfig.f_NeedExpCount) then
                _M.boxMaxCount = boxConfig.f_NeedExpCount;
            end
            tempNum.text = boxConfig.f_NeedExpCount;
            local statusController = _M.boxReward[i]:GetController("status");
            statusController.selectedIndex = 0;
            table.insert(_M.boxStatus, statusController);
            table.insert(_M.boxRewardItem, _M.boxReward[i]:GetChild("item"));
            --table.insert(_M.boxRewardItemCtrl, CtrlManager.GetCtrl(PanelNames.Item));
        end
        
        local specialRewardDay = 30;
        local globalConfig = G.dataTable["t_global"]["304"];
        if globalConfig ~= nil then
            specialRewardDay = globalConfig.f_int_value;
        end
        local createTime = os.date("%Y-%m-%d %H:%M:%S",tonumber(logicMgr.HeroManager.GetRoleInfo().createTime));
        date = "%d%d:%d%d:%d%d"
        createTime = string.sub(createTime, string.find(createTime, date));
        local hour = tonumber(string.sub(createTime,1, 2));
        local min = tonumber(string.sub(createTime,4, 5));
        local sec = tonumber(string.sub(createTime,7, 8));
        if hour < 5 then
            _M.specialRewardEndTime = tonumber(logicMgr.HeroManager.GetRoleInfo().createTime) + tonumber(specialRewardDay - 1) * 24 * 3600 + (5 - hour) * 3600 - min * 60 - sec;
        else
            _M.specialRewardEndTime = tonumber(logicMgr.HeroManager.GetRoleInfo().createTime) + tonumber(specialRewardDay) * 24 * 3600 - (hour - 5) * 3600 - min * 60 - sec;
        end
        _M.endCountDown = _M.specialRewardEndTime - HelperFunc.GetServerTime();
        if _M.endCountDown > 0 then
            self:updateActiveCountDown();
            self:TimeCall(self.updateActiveCountDown, 1000, -1);
        end
    end
    
    local score = self.serverData.param.score;
    if score == nil then
        score = 0;
    end
    local boxRewardedSet = self.serverData.param.boxRewardedSet;
    local boxCompleteTimeMap = self.serverData.param.boxCompleteTimeMap;
    local hasGet = false;
    for i = 1, #self.boxReward do
        local index = i;
        local isSpecialReward = true;
        self.boxReward[index].visible = false;
        local taskBoxConfig = _M.assembleTaskBoxConfig[tostring(index)];
        local rewards;
        if tonumber(taskBoxConfig.f_Change) == 1 then
            if _M.specialRewardEndTime > HelperFunc.GetServerTime() then
                rewards = decodeJsonStrToTabel(taskBoxConfig.f_BoxAward)
            else
                self.countDown.visible = false;
                if boxCompleteTimeMap ~= nil and #boxCompleteTimeMap > 0 then
                    for boxCompleteTimeK, boxCompleteTimeV in pairs(boxCompleteTimeMap) do
                        if tonumber(index) == tonumber(boxCompleteTimeK) then
                            if tonumber(boxCompleteTimeV) <= tonumber(_M.specialRewardEndTime) then
                                rewards = decodeJsonStrToTabel(taskBoxConfig.f_BoxAward)
                            else
                                rewards = decodeJsonStrToTabel(taskBoxConfig.f_OtherAward)
                                isSpecialReward = false;
                            end
                            break;
                        end
                    end
                else
                    rewards = decodeJsonStrToTabel(taskBoxConfig.f_OtherAward)
                    isSpecialReward = false;
                end
            end
            if rewards == nil then
                rewards = decodeJsonStrToTabel(taskBoxConfig.f_OtherAward)
                isSpecialReward = false;
            end
            
            --[[
            if _M.heroId == nil and #rewards > 0 and isSpecialReward then
                local itemConfig = G.dataTable["t_item"][tostring(rewards[1][1])];
                if itemConfig ~= nil then
                    local scriptId = itemConfig.f_ScriptId
                    if scriptId ~= nil and scriptId > 0 then
                        local dropConfig = G.dataTable["t_drop"][tostring(scriptId)];
                        if dropConfig ~= nil then
                            if dropConfig.f_Hero ~= nil then
                                local heroData = decodeJsonStrToTabel(dropConfig.f_Hero)
                                if heroData ~= nil and #heroData > 0 then
                                    _M.heroId = heroData[1][1];
                                end
                            end
                        end
                    end
                end
            end
            --]]
        else
            rewards = decodeJsonStrToTabel(taskBoxConfig.f_BoxAward)
        end
        --if #rewards > 0 and _M.boxRewardItemCtrl[index] ~= nil and _M.boxRewardItem[index] ~= nil then
        if #rewards > 0 and _M.boxRewardItem[index] ~= nil then
            _M.boxRewardItem[i].onClick:Clear();
            self.boxReward[index].visible = true;
            logicMgr.CostManager.RefreshItem(_M.boxRewardItem[index], rewards[1], {isShowBigNum = true})
            --_M.boxRewardItemCtrl[index].initData(_M.boxRewardItem[index],logicMgr.CostManager.getItemOrEquipDataByIdAndNum(rewards[1][1], rewards[1][2]));
            if tonumber(score) < tonumber(taskBoxConfig.f_NeedExpCount) then
                if _M.boxStatus[index] ~= nil then
                    _M.boxStatus[index].selectedIndex = 0;
                end
                if tonumber(taskBoxConfig.f_Change) == 1 then
                    if isSpecialReward then
                       -- _M.boxRewardItemCtrl[index].DisableClick(_M.boxRewardItem[index]);
                        _M.boxRewardItem[index].onClick:Clear()
                        _M.boxRewardItem[index].onClick:Add(function ()
                            --showUI(PanelNames.UIHeroCollectTips, _M.heroId)
                            showUI(PanelNames.UIHeroCollectTips)
                        end);
                    end
                end
            else
                hasGet = false;
                if boxRewardedSet ~= nil then
                    for boxK, boxV in pairs(boxRewardedSet) do
                        if tonumber(index) == tonumber(boxV) then
                            hasGet = true;
                            break;
                        end
                    end
                end
                
                if hasGet then
                    if _M.boxStatus[index] ~= nil then
                        _M.boxStatus[index].selectedIndex = 2;
                    end
                    if tonumber(taskBoxConfig.f_Change) == 1 then
                        if isSpecialReward then
                           -- _M.boxRewardItemCtrl[index].DisableClick(_M.boxRewardItem[index]);
                            _M.boxRewardItem[index].onClick:Clear();
                            _M.boxRewardItem[index].onClick:Add(function ()
                                --showUI(PanelNames.UIHeroCollectTips, _M.heroId)
                                showUI(PanelNames.UIHeroCollectTips)
                            end);
                        end
                    end
                else
                    if _M.boxStatus[index] ~= nil then
                        _M.boxStatus[index].selectedIndex = 1;
                    end
                    --_M.boxRewardItemCtrl[index].DisableClick(_M.boxRewardItem[index]);
                    _M.boxRewardItem[index].onClick:Clear();
                    _M.boxRewardItem[index].onClick:Add(function ()
                        if not _M.isGetReward then
                            _M.isGetReward = true;
                            ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, 2, index});
                            TAManager.TrackByDictionary("assembly_task_draw_box", {box_id = index, change = taskBoxConfig.f_Change})
                            self:TimeCall(self.GetRewardTimeEnd, 100);
                        end
                    end);
                end
            end
        end
    end
    self.totalTaskInfo.text = tostring(score);
    self.boxProgress.value = math.min(tonumber(score) / tonumber(_M.boxMaxCount) * 100, 100);
    self.firstBoxProgress.value = math.min(tonumber(score) / tonumber(_M.firstBoxCount) * 100, 100);
end

function _M:GetRewardTimeEnd()
    self:RemoveTimeCall(self.GetRewardTimeEnd);
    _M.isGetReward = false;
end

function _M.RefreshTaskItem(index, itemObj)
    _M:CreateTaskItem(index,itemObj)
    local taskId = _M.assembleTaskList[_M.selectIndex + 1][index +  1][1];
    _M.ContentItems[index]:OnShow(taskId, _M.assembleTaskServerData[tostring(taskId)])
end

function _M:CreateTaskItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = self.HeroCollectTaskItem.New()
    self.ContentItems[index] = item
    item:OnCreate(itemObj,self)
end

-- 隐藏
function _M:OnDisable()
    self:RemoveTimeCall(self.updateActiveCountDown);
end

function _M:updateActiveCountDown()
    if _M.endCountDown == nil or _M.endCountDown < 0 then
        self:RemoveTimeCall(self.updateActiveCountDown);
        _M:RefreshBox();
    end
    local time_str = "";
    local surpDay = math.floor(_M.endCountDown / 24 / 3600)
    if surpDay > 0 then
        time_str = string.format(getLanguage("ActivityTips10501"), string.format(getLanguage("Sys_Time_Day"),surpDay))
    else
        local surpHour = math.floor(_M.endCountDown / 3600)
        if surpHour > 0 then
            time_str = string.format(getLanguage("ActivityTips10501"), string.format(getLanguage("Sys_Time_Hour"),surpHour))
        else
            local surpMin = math.floor(_M.endCountDown / 60)
            if surpMin > 0 then
                time_str = string.format(getLanguage("ActivityTips10501"), string.format(getLanguage("Sys_Time_Minute"),surpMin))
            else
                time_str = string.format(getLanguage("ActivityTips10501"), string.format(getLanguage("Sys_Time_Minute"),_M.endCountDown))
            end
        end
    end

    if self.update_active_count_down_content == nil or self.update_active_count_down_content ~= time_str then
        self.countDown.text = time_str
        self.update_active_count_down_content = time_str
    end
   
   _M.endCountDown = _M.endCountDown - 1 
end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    if self.ContentItems then
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy()
        end
        self.ContentItems = nil
    end

    for i = 1, #self.boxReward do
        _M.boxRewardItem[i].onClick:Clear();
    end
    _M.hasInit = false
    _M.ContentItems = {}
    _M.selectIndex = 0
    _M.tabRed = {}
    _M.activeId = nil
    _M.assembleTaskList = nil
    _M.assembleTaskBoxConfig = nil
    _M.boxStatus = nil
    _M.boxRewardItem = nil
   -- _M.boxRewardItemCtrl = nil
  --  _M.heroId = nil
    _M.boxMaxCount = 0;
    _M.specialRewardEndTime = 0;
    _M.endCountDown = 0;
    _M.lastRewardedTime = -1;
    _M.rewardedNum = 0;
    _M.taskNum = 0;
    _M.hasTaskReward = false;
end

-- 任务类
_M.HeroCollectTaskItem = Class("HeroCollectTaskItem",UIComponentInterface)
local _M_T = _M.HeroCollectTaskItem
function _M_T:OnCreate(obj,parent)
    self.taskId = 0
    self.taskData = nil;
    self.parent = parent
    self.fguiObj = obj
    self.isGet = false;
    self.breakStone = nil;

    self.quality = obj:GetChild("quality")
    self.qualityFrame = self.quality:GetChild("frame")
    self.qualityIcon = self.quality:GetChild("icon")
    self.qualityNumIcon = self.quality:GetChild("numIcon")
    self.staegeController = self.quality:GetController("jinjie")
    self.maxController = self.quality:GetController("LR");
    
    self.rewardItem = obj:GetChild("Item")
    self.taskName = obj:GetChild("TaskName")
    self.rewardNum = obj:GetChild("num")
    self.btnGo = obj:GetChild("btn_Go")
    self.btnGet = obj:GetChild("btn_Get")
    self.statusController = obj:GetController("status")
    self.coordinates = obj:GetController("coordinates")
    self.progress = obj:GetChild("bar")
    self.processLab = obj:GetChild("scheduleText")
    
    self.parent:RegisterOnClick(self.btnGo,self.ClickGoto,self)
    self.parent:RegisterOnClick(self.btnGet,self.ClickReward,self)
end
function _M_T:OnShow(taskId, taskData)
    self.taskId = taskId;
    self.taskData = taskData
    self:Refresh()
end

function _M_T:Refresh()
    local assembleTask = G.dataTable["t_assembletask"][tostring(self.taskId)];
    local star = 20
    if assembleTask.f_EndRank ~= nil and assembleTask.f_EndRank > 10 then
        star =logicMgr.HeroManager.starToQuality(tonumber(assembleTask.f_EndRank))
    else
        star =logicMgr.HeroManager.starToQuality(tonumber(assembleTask.f_StartRank))
    end
    local config = G.dataTable.t_iconframe[tostring(star)]
    local isFrame = config.f_Ornaments ~= ""
    self.qualityFrame.visible = isFrame
    local atlas = "ui://CharactorUI/"
    if isFrame then
        self.qualityFrame.url = atlas .. config.f_QualityOrnaments
    end
    if config.f_QualityText ~= "" then
        self.qualityIcon.url = atlas .. config.f_QualityText
        self.staegeController.selectedIndex = 1;
        self.coordinates.selectedIndex = 1;
    else
        self.staegeController.selectedIndex = 0;
        self.coordinates.selectedIndex = 0;
    end
    if self.quality ~= nil then
        local quality = tonumber(config.f_Quality);
        if self.breakStone ~= nil then
            self.breakStone:destroy();
            self.breakStone = nil;
        end
        self.breakStone = UIBreakStone:new(self.quality);
        self.breakStone:setQuality(quality);
    end
    self.qualityNumIcon.url = atlas .. config.f_QualityIcon
    if config.f_Id > 10 then
        self.staegeController.selectedIndex = 0;
        self.coordinates.selectedIndex = 2;
        self.maxController.selectedIndex = star - 10;
    else
        self.maxController.selectedIndex = 0;
    end

    local rewards = decodeJsonStrToTabel(assembleTask.f_Award)
    if #rewards > 0 then
        logicMgr.CostManager.RefreshItem(self.rewardItem, rewards[1]);
    else
        self.rewardItem.visible = false;
    end

    self.taskName.text = getLanguage(assembleTask.f_AssembleTaskDesc);
    self.rewardNum.text = tostring(assembleTask.f_ExpCount);
    if self.taskData.rewarded then
        self.statusController.selectedIndex = 2;
        self.processLab.text = tostring(assembleTask.f_Progress).."/"..tostring(assembleTask.f_Progress);
        self.progress.value = 100;
    else
        local count = math.min(tonumber(self.taskData.process), tonumber(assembleTask.f_Progress));
        self.processLab.text = tostring(count) .. "/" .. tostring(assembleTask.f_Progress);
        self.progress.value = math.min(tonumber(self.taskData.process) / tonumber(assembleTask.f_Progress) * 100, 100);
        if tonumber(self.taskData.process) < tonumber(assembleTask.f_Progress) then
            self.statusController.selectedIndex = 0;
        else
            self.statusController.selectedIndex = 1;
        end
    end
end

function _M_T:OnHide()

end
function _M_T:OnDestroy()
   -- self.itemList = nil
    if self.breakStone ~= nil then
        self.breakStone:destroy();
        self.breakStone = nil;
    end
end

function _M_T:ClickGoto()
    closeUI(self.parent._panelName)
    closeUI(PanelNames.UIActivity)
    showUI(PanelNames.UIHeadMenu);
    logicMgr.FuncOpenManager.jump(4)
end

function _M_T:ClickReward()
    if self.isGet then
        return;
    end

    self.isGet = true;
    self:TimeCall(self.TimeEnd, 100);
    
    ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, 1, tonumber(self.taskId)});

    local excel = G.dataTable["t_assembletask"][tostring(self.taskId)]
    if excel then
        TAManager.TrackByDictionary("assembly_task_draw_reward", {assembletask_id = excel.f_AssembleTaskId, task_exp_count = excel.f_ExpCount})
    end
    
end

function _M_T:TimeEnd()
    self:RemoveTimeCall(self.TimeEnd)
    self.isGet = false;
end

return _M;